<template>
  <div class="app-container">
    <custom-query ref="query" id="query" :items="items" @query="query"></custom-query>
    <custom-table-grid ref="grid"
                       :column-data="columndata1"
                       :is-need-check-box="false"
                       url="/common/operator/operatorGetOpers"
                       :toolbar="toolbar">
    </custom-table-grid>
    <el-dialog :title="title" width="65%" :visible.sync="commonDialog">
      <custom-form ref="common" id="common" :items="commonItems" :default-value="defaultData"></custom-form>
      <span slot="footer">
        <custom-btn btn-type="cancel" @btn-click="commonDialog = false" :label="this.$t('common.cancel')"></custom-btn>
        <custom-btn btn-type="confirm" @btn-click="confirm" :label="this.$t('common.confirm')"></custom-btn>
      </span>
    </el-dialog>
    <el-dialog :title="_$Z['configRole']" width="50%" :visible.sync="configRoleDialog" class="roleDialog">
      <info-form :information="information"></info-form>
      <div class="roleLeft">
        <custom-table-grid ref="roleGrid"
                           :column-data="columndata2"
                           url="/common/operator/operatorGetRoles"
                           :footer="footer"
                           :suportExport="false">
        </custom-table-grid>
      </div>
      <div class="roleRight">
        <custom-table-grid ref="choosenRoleGrid"
                           :column-data="columndata3"
                           url="/common/operator/operatorGetChoosenRoles"
                           :footer="null">
        </custom-table-grid>
      </div>
    </el-dialog>
  </div>
</template>

<style lang="scss">
  .roleLeft {
    width: 49%;
    height: 500px;
    overflow: auto;
    display: inline-block;
    .el-card {
      margin: 0 !important;
    }
  }

  .roleRight {
    width: 49%;
    height: 500px;
    overflow: auto;
    display: inline-block;
    margin-left: 1.3%;
    .el-card {
      margin: 0 !important;
    }
  }

  .roleDialog {
    .el-dialog {
      margin-top: 8vh !important;
    }
    .el-card__body {
      padding: 0;
    }
  }

  .vue-treeselect__menu {
    max-height: 260px !important;
  }

</style>

<script>
import customQuery from '@/views/platform/components/queryCondition/customQuery'
import customTableGrid from '@/views/platform/components/tableGrid/customTableGrid'
import customForm from '@/views/platform/components/multiForm/customForm'
import infoForm from '@/views/platform/components/multiForm/infoDisplayForm'
import { post } from '@/api/common'

export default {
  name: 'platform_authority_operator',
  components: { customQuery, customTableGrid, customForm, infoForm },
  data() {
    const start = new Date()
    const end = new Date()
    start.setMonth(start.getMonth() + 1)
    const defaultTime = [start, end]
    const queryType = {
      show: true,
      needDefault: true,
      isMulti: false,
      org: ['org']
    }
    return {
      i18Keys: ['add', 'edit', 'configRole', 'operator', 'resetPassword', 'confirmResetPassword', 'effectiveDateIllegal', 'loginTimeIllegal'],
      queryType: queryType,
      defaultTime: defaultTime,
      items: [
        { label: 'unit', elType: 'node', id: 'node', supportType: queryType, validator: { required: true }},
        { label: 'name2', elType: 'input', id: 'name', validator: { spChar: true, length: [-1, 128] }},
        { label: 'status', elType: 'select', id: 'status', codeType: 'oper_status_type', isAll: false }
      ],
      commonItems: [],
      defaultData: {},
      param: {},
      columndata1: [
        { label: 'userName', prop: 'NO' },
        { label: 'name2', prop: 'NAME' },
        { label: 'status', prop: 'STATUS', type: 'switch', activeValue: '1', inactiveValue: '0', callback: this.statusChange },
        { label: 'phoneNumber', prop: 'PHONE' },
        { label: 'email', prop: 'EMAIL' },
        { label: 'role', prop: 'ROLE_NAME' },
        { label: 'operation', prop: 'OP', type: 'operations', width: 164, operations: [
          { type: 'edit', label: 'edit', method: this.editOper },
          { type: 'set', label: 'configRole', method: this.configRole },
          { type: 'resetPassword', label: 'resetPassword', method: this.resetPassword },
          { type: 'delete', label: 'delete', method: this.deleteOper }
        ] }
      ],
      columndata2: [
        { label: 'name2', prop: 'NAME', sort: false },
        { label: 'operation', prop: 'OP', type: 'operations', width: 90, operations: [
          { type: 'plus', label: '', method: this.bindRole, filterMethod: this.bindCheck }
        ] }
      ],
      columndata3: [
        { label: 'choosenRole', prop: 'NAME', sort: false },
        { label: 'operation', prop: 'OP', type: 'operations', width: 90, operations: [
          { type: 'minus', label: '', method: this.unBindRole }
        ] }
      ],
      toolbar: [
        { type: 'add', label: 'add', method: this.addOper }
      ],
      title: '',
      pageType: '',
      commonDialog: false,
      configRoleDialog: false,
      information: [],
      operId: '',
      operNo: '',
      footer: {
        pagerCount: 5,
        layout: 'prev, pager, next'
      }
    }
  },
  methods: {
    // 查询操作员
    query(value) {
      if (value.node === null || value.node === '' || value.node.objectIds.length === 0) {
        this.$message({
          message: this.$t('common.selectOrg'),
          type: 'warning',
          center: true
        })
        return
      }
      this.param = {
        node: value.node,
        name: value.name,
        status: value.status
      }
      this.$refs.grid.pageQuery(this.param)
    },

    // 新增操作员
    addOper() {
      this.title = this._$Z['add']
      this.pageType = 'add'
      this.defaultData = {
        org: typeof (this.param.node) === 'undefined' ? null : this.param.node.objectIds[0],
        status: false
      }
      this.commonItems = [
        { label: 'userName', elType: 'input', id: 'no', validater: '{ "required": true, "length": [-1, 32] }' },
        { label: 'unit', elType: 'org', id: 'org', validater: '{ "required": true }' },
        { label: 'name2', elType: 'input', id: 'name', validater: '{ "required": true, "length": [-1, 32] }' },
        { label: 'password', elType: 'input', id: 'password1', type: 'password', clear: true, validater: '{ "required": true, "length": [6, 32] }' },
        { label: 'phoneNumber', elType: 'input', id: 'phone', validater: '{ "length": [-1, 32] }' },
        { label: 'confirmPassword', elType: 'input', id: 'password2', type: 'password', clear: true, validater: '{ "required": true, "length": [6, 32] }' },
        { label: 'email', elType: 'input', id: 'email', validater: '{ "email": true, "length": [-1, 32] }' },
        { label: 'IP', elType: 'input', id: 'ip', clear: true, validater: '{ "ip": true }' },
        { label: 'effectiveTime', elType: 'ndatetime', id: 'effectiveDate', clear: false },
        { label: 'effectiveLoginTime', elType: 'time', id: 'loginTime' },
        { label: 'status', elType: 'switch', id: 'status' }
      ]
      this.commonDialog = true
      setTimeout(() => { // 延时删除校验
        this.$refs.common.clearValidate()
      }, 0)
    },

    // 编辑操作员
    editOper(index, row) {
      this.title = this._$Z['edit']
      this.pageType = 'edit'
      this.defaultData = {
        id: row.ID,
        no: row.NO,
        org: row.ORG_NO,
        name: row.NAME,
        phone: row.PHONE,
        email: row.EMAIL,
        ip: row.BIND_IP,
        status: row.STATUS === '1'
      }
      if (row.EFFECTIVE_TIME_START != null && row.EFFECTIVE_TIME_END !== null) {
        this.defaultData.effectiveDate = [new Date(row.EFFECTIVE_TIME_START), new Date(row.EFFECTIVE_TIME_END)]
      }
      if (row.LOGIN_TIME_START !== null && row.LOGIN_TIME_END !== null) {
        this.defaultData.loginTime = [row.LOGIN_TIME_START, row.LOGIN_TIME_END]
      }
      this.commonItems = [
        { label: 'userName', elType: 'input', id: 'no', disabled: true, validater: '{ "required": true, "length": [-1, 32] }' },
        { label: 'unit', elType: 'org', id: 'org', supportType: this.queryType, validater: '{ "required": true }' },
        { label: 'name2', elType: 'input', id: 'name', validater: '{ "required": true, "length": [-1, 32] }' },
        { label: 'phoneNumber', elType: 'input', id: 'phone' },
        { label: 'email', elType: 'input', id: 'email', validater: '{ "email": true, "length": [-1, 32] }' },
        { label: 'IP', elType: 'input', id: 'ip', clear: true, validater: '{ "ip": true }' },
        { label: 'effectiveTime', elType: 'ndatetime', id: 'effectiveDate', clear: false },
        { label: 'effectiveLoginTime', elType: 'time', id: 'loginTime' },
        { label: 'status', elType: 'switch', id: 'status' }
      ]
      this.commonDialog = true
      setTimeout(() => { // 延时删除校验
        this.$refs.common.clearValidate()
      }, 0)
    },

    // 删除操作员
    deleteOper(index, row) {
      this.$confirm(this.$t('message.confirmDelete'), this.$t('common.prompt'), {
        confirmButtonText: this.$t('common.confirm'),
        cancelButtonText: this.$t('common.cancel')
      }).then(() => {
        post('/common/operator/operatorDeleteOper', { id: row.ID, no: row.NO }).then(response => {
          this.$message({
            type: 'success',
            message: this.$t('message.deleteSuccess')
          })
          this.$refs.query.queryClick()
        })
      }).catch(() => {
        return
      })
    },

    // 配置角色
    configRole(index, row) {
      this.configRoleDialog = true
      this.operId = row.ID
      this.operNo = row.NO
      this.information = [
        { title: '', items: [{ label: this._$Z['operator'], value: row.NAME, color: '#f36a5a' }] }
      ]
      setTimeout(() => {
        this.$refs.roleGrid.pageQuery({ id: row.ID })
        this.$refs.choosenRoleGrid.pageQuery({ id: row.ID })
      }, 0)
    },

    // 重置密码
    resetPassword(index, row) {
      this.$confirm(this._$Z['confirmResetPassword'], this.$t('common.prompt'), {
        confirmButtonText: this.$t('common.confirm'),
        cancelButtonText: this.$t('common.cancel')
      }).then(() => {
        post('/common/operator/operatorResetPassword', { id: row.ID, no: row.NO }).then(response => {
          this.$message({
            type: 'success',
            message: this.$t('message.operateSuccess')
          })
          // this.$refs.query.queryClick()
        })
      }).catch(() => {
        return
      })
    },

    // 绑定角色
    bindRole(index, row) {
      const param = {
        id: this.operId,
        no: this.operNo,
        roleId: row.ROLE_ID,
        relId: row.REL_ID
      }
      post('/common/operator/operatorBindRole', param).then(response => {
        this.$message({
          type: 'success',
          message: this.$t('message.bindSuccess')
        })
        this.$refs.roleGrid.pageQuery({ id: this.operId })
        this.$refs.choosenRoleGrid.pageQuery({ id: this.operId })
        // this.$refs.query.queryClick()
      })
    },

    // 绑定过滤
    bindCheck(row) {
      if (row.USER_ID !== null) {
        return false
      } else {
        return true
      }
    },

    // 解除绑定
    unBindRole(index, row) {
      post('/common/operator/operatorUnBindRole', { id: row.ID, no: this.operNo }).then(response => {
        this.$message({
          type: 'success',
          message: this.$t('message.unBindSuccess')
        })
        this.$refs.roleGrid.pageQuery({ id: this.operId })
        this.$refs.choosenRoleGrid.pageQuery({ id: this.operId })
        // this.$refs.query.queryClick()
      })
    },

    // 保存
    confirm() {
      this.$refs.common.checkForm(this.save)
    },

    // 表单校验成功调用方法
    save(param) {
      if (param.password1 !== param.password2) { // 密码确认检查
        this.$message({
          type: 'warning',
          message: this.$t('message.passwordNotSame')
        })
        return
      }
      if (param.no === 'admin') { // 超级管理员检查
        this.$message({
          type: 'warning',
          message: this.$t('message.superAdmin')
        })
        return
      }

      if (param.effectiveDate && param.effectiveDate.length > 1 && param.effectiveDate[0] >= param.effectiveDate[1]) {
        this.$message({
          type: 'warning',
          message: this._$Z['effectiveDateIllegal']
        })
        return
      }
      if (param.loginTime && param.loginTime.length > 1 && param.loginTime[0] >= param.loginTime[1]) {
        this.$message({
          type: 'warning',
          message: this._$Z['loginTimeIllegal']
        })
        return
      }

      post('/common/operator/operatorCheckUsername', { operType: this.pageType, no: param.no }).then(response => {
        let url = ''
        param.effectiveStart = param.effectiveDate !== null ? param.effectiveDate[0] : null
        param.effectiveEnd = param.effectiveDate !== null ? param.effectiveDate[1] : null
        param.loginStart = param.loginTime !== null ? param.loginTime[0] : null
        param.loginEnd = param.loginTime !== null ? param.loginTime[1] : null
        param.status = param.status === false ? '0' : '1'
        if (this.pageType === 'add') {
          param.password = param.password1
          url = '/common/operator/operatorAddOper'
        } else {
          url = '/common/operator/operatorEditOper'
        }
        post(url, param).then(response => {
          this.$message({
            type: 'success',
            message: this.$t('message.saveSuccess')
          })
          this.commonDialog = false
          // this.$refs.grid.pageQuery(this.param)
          this.$refs.query.queryClick()
        })
      })
    },

    // 切换状态
    statusChange(value, row) {
      const param = {
        id: row.ID,
        no: row.NO,
        value: value
      }
      post('/common/operator/operatorUpdateOperStatus', param).then(response => {
        this.$message({
          type: 'success',
          message: this.$t('message.operateSuccess')
        })
        this.commonDialog = false
        setTimeout(() => {
          this.$refs.grid.pageQuery(this.param)
        }, 200)
      })
    }
  }
}
</script>